//
//  TrackitDataEngine.m
//  Trackit
//
//  Created by yaodaobin on 2017/4/8.
//  Copyright © 2017年 yaodaobin. All rights reserved.
//

#import "TrackitDataEngine.h"

@implementation TrackitDataEngine

+ (TrackitDataEngine *)sharedClient {
    static dispatch_once_t onceToken;
    static TrackitDataEngine *instance;
    dispatch_once(&onceToken, ^{
        instance = [[TrackitDataEngine alloc] initWithBaseURL:[NSURL URLWithString:API_BASE_URL]];
    });
    return instance;
}

+ (TrackitDataEngine *)imageUploadSharedClient {
    static dispatch_once_t onceToken;
    static TrackitDataEngine *instance;
    dispatch_once(&onceToken, ^{
        instance = [[TrackitDataEngine alloc] initWithBaseURL:[NSURL URLWithString:API_BASE_URL]];
    });
    return instance;
}

- (id)initWithBaseURL:(NSURL *)url {
    self = [super initWithBaseURL:url];
    
    if (!self){
        return nil;
    }
    self.requestSerializer = [AFHTTPRequestSerializer serializer];
    
    return self;
}

- (NSURLSessionDataTask *)getPath:(NSString *)URLString
                       parameters:(id)parameters
                          success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
                          failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure {
    return [self GET:URLString ? : @"" parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:success failure:failure];
}

- (NSURLSessionDataTask *)postPath:(NSString *)URLString
                        parameters:(id)parameters
                           success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
                           failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure {
    return [self POST:URLString ? : @"" parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
    } success:success failure:failure];
}

- (NSURLSessionDataTask *)postPath:(NSString *)URLString
                        parameters:(id)parameters
         constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block
                           success:(void (^)(NSURLSessionDataTask *task, id responseObject))success
                           failure:(void (^)(NSURLSessionDataTask *task, NSError *error))failure {
    return [self POST:URLString ? : @"" parameters:parameters constructingBodyWithBlock:block progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:success failure:failure];
    
}

+ (void)onComplete:(void (^)(NSDictionary *data, NSError *error))block operation:(NSURLSessionDataTask *)operation json:(id)JSON error:(NSError **)outError {
    NSError *error;
#if (defined(DEBUG) || defined(ADHOC))
    @try {
        NSString *jsonString = nil;
        if (JSON) {
            NSError *serializerError ;
            NSData *responesData = [NSJSONSerialization dataWithJSONObject:JSON options: NSJSONWritingPrettyPrinted error:&serializerError];
            if (!serializerError) {
                jsonString = [[NSString alloc] initWithData:responesData encoding:((AFJSONResponseSerializer *)([self sharedClient].responseSerializer)).stringEncoding];
            } else {
                DLog(@"jsonError:%@",serializerError);
            }
            DLog(@"服务器返回数据:%@",jsonString);
        }
        
    }
    @catch (NSException *exception) {
        DLog(@"jsonErrorexception:%@",exception);
    }
    @finally {
        
    }
#endif
    id data;
    if ([[JSON valueForKeyPath:@"Success"] boolValue]) {
        data = JSON;
    } else {
        
        NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
        id message = [JSON valueForKey:@"Msg"];
        
        if (message) {
            [userInfo setObject:message forKey:@"message"];
        }
        if (JSON) {
            [userInfo setObject:JSON forKey:@"data_api"];
        }
        
        error = [[NSError alloc] initWithDomain:@"API"
                                           code:-100
                                       userInfo:userInfo];
        
    }
    
    if (block) {
        block(data, error);
    }
}

+ (NSMutableDictionary *)rebuildParameter:(NSMutableDictionary *)parameters {
    if (APP_DELEGATE.user) {
        [parameters safeSetObject:APP_DELEGATE.user.userName forKey:@"username"];
        [parameters safeSetObject:APP_DELEGATE.user.password forKey:@"password"];
    }
    return parameters;
}
#pragma mark - Buisness
+ (void)appLoginAction:(NSMutableDictionary *)parameters onComplete:(void (^)(NSDictionary *data, NSError *error))block {
    parameters = [self rebuildParameter:parameters];
    [[TrackitDataEngine sharedClient] postPath:@"/PastureSpace/Mobile/Login" parameters:parameters success:^(NSURLSessionDataTask *operation,id JSON) {
        [self onComplete:block operation:operation json:JSON error:nil];
    } failure:^(NSURLSessionDataTask *operation,NSError *error) {
        if (block) {
            block(nil, error);
        }
    }];
}

+ (void)getTaskList:(NSMutableDictionary *)parameters onComplete:(void (^)(NSDictionary *data, NSError *error))block {
    parameters = [self rebuildParameter:parameters];
    [[TrackitDataEngine sharedClient] postPath:@"/PastureSpace/Mobile/GetTaskDetailList" parameters:parameters success:^(NSURLSessionDataTask *operation,id JSON) {
        [self onComplete:block operation:operation json:JSON error:nil];
    } failure:^(NSURLSessionDataTask *operation,NSError *error) {
        if (block) {
            block(nil, error);
        }
    }];
}

+ (void)getTaskDetail:(NSMutableDictionary *)parameters onComplete:(void (^)(NSDictionary *data, NSError *error))block {
    parameters = [self rebuildParameter:parameters];
    [[TrackitDataEngine sharedClient] postPath:@"/PastureSpace/Mobile/GetTaskDetail" parameters:parameters success:^(NSURLSessionDataTask *operation,id JSON) {
        [self onComplete:block operation:operation json:JSON error:nil];
    } failure:^(NSURLSessionDataTask *operation,NSError *error) {
        if (block) {
            block(nil, error);
        }
    }];
}
+ (void)submitTaskDetail:(NSMutableDictionary *)parameters onComplete:(void (^)(NSDictionary *data, NSError *error))block {
    parameters = [self rebuildParameter:parameters];
    [[TrackitDataEngine sharedClient] postPath:@"/PastureSpace/Mobile/SubmitTaskDetail" parameters:parameters success:^(NSURLSessionDataTask *operation,id JSON) {
        [self onComplete:block operation:operation json:JSON error:nil];
    } failure:^(NSURLSessionDataTask *operation,NSError *error) {
        if (block) {
            block(nil, error);
        }
    }];
}

+ (void)completeTaskDetail:(NSMutableDictionary *)parameters onComplete:(void (^)(NSDictionary *data, NSError *error))block {
    parameters = [self rebuildParameter:parameters];
    [[TrackitDataEngine sharedClient] postPath:@"/PastureSpace/Mobile/CompleteTaskDetail" parameters:parameters success:^(NSURLSessionDataTask *operation,id JSON) {
        [self onComplete:block operation:operation json:JSON error:nil];
    } failure:^(NSURLSessionDataTask *operation,NSError *error) {
        if (block) {
            block(nil, error);
        }
    }];
}

+ (void)uploadPhoto:(NSData *)imageData withParams:(NSMutableDictionary *)parameters onComplete:(void (^)(NSDictionary *data, NSError *error))block {
    parameters = [self rebuildParameter:parameters];
    
    for (int i = 0; i < parameters.allValues.count; i++) {
        NSString *key = parameters.allKeys[i];
        NSString *value = parameters.allValues[i];
        [[TrackitDataEngine imageUploadSharedClient].requestSerializer setValue:value forHTTPHeaderField:key];
    }
    
    [[TrackitDataEngine imageUploadSharedClient] postPath:@"/PastureSpace/Mobile/UploadPhoto" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileData:imageData name:@"pic" fileName:@"t.jpg" mimeType:@"image/jpeg"];
    } success:^(NSURLSessionDataTask *task, id responseObject) {
        [self onComplete:block operation:task json:responseObject error:nil];
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        if (block) {
            block(nil, error);
        }
    }];

}

#pragma mark -- GET请求 --
+ (void)getWithURLString:(NSString *)URLString
              parameters:(id)parameters
                 success:(void (^)(NSDictionary * dictionary))success
                 failure:(void (^)(NSError * error))failure {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = 10;
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json", @"text/plain", @"text/html", nil];
    [manager GET:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (responseObject) {
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (error) {
            failure(error);
        }
    }];
}

#pragma mark -- POST请求 --
+ (void)postWithURLString:(NSString *)URLString
               parameters:(id)parameters
                  success:(void (^)(id))success
                  failure:(void (^)(NSError *))failure {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = 10;
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json", @"text/plain", @"text/html", nil];
    [manager POST:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
    }];
}

#pragma mark -- 上传图片 --
+ (void)uploadWithURLString:(NSString *)URLString
                 parameters:(id)parameters
                 uploadData:(NSData *)uploadData
                 uploadName:(NSString *)uploadName
                    success:(void (^)())success
                    failure:(void (^)(NSError *))failure {
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json", @"text/plain", @"text/html", nil];
    [manager POST:URLString parameters:parameters constructingBodyWithBlock:^(id< AFMultipartFormData >  _Nonnull formData) {
        [formData appendPartWithFileData:uploadData name:uploadName fileName:uploadName mimeType:@"image/png"];
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
    }];
}

// 上传多张图片
+ (void)uploadMostImageWithURLString:(NSString *)URLString
                          parameters:(id)parameters
                         uploadDatas:(NSArray *)uploadDatas
                          uploadName:(NSString *)uploadName
                             success:(void (^)())success
                             failure:(void (^)(NSError *))failure{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/json", @"text/plain", @"text/html", nil];
    [manager POST:URLString parameters:parameters constructingBodyWithBlock:^(id< AFMultipartFormData >  _Nonnull formData) {
        for (int i = 0; i < uploadDatas.count; i++) {
            NSString *imageName = [NSString stringWithFormat:@"%@[%i]", uploadName, i];
            [formData appendPartWithFileData:uploadDatas[i] name:uploadName fileName:imageName mimeType:@"image/png"];
        }
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (success) {
            success(responseObject);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (failure) {
            failure(error);
        }
    }];
}

@end
